import { Injectable, UnauthorizedException } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { UserService } from 'src/feature/user/user.service';
import { CryptoUtil } from 'src/common/utils/crypto.util';

@Injectable()
export class AuthService {
  constructor(
    private readonly userService: UserService,
    private readonly jwtService: JwtService,
    private readonly cryptoUtil: CryptoUtil,
  ) {}

  /**
   * 验证用户凭据并生成token
   * @param account 账户名
   * @param password 密码
   * @returns 用户信息和token
   */
  async validateUserAndGenerateToken(
    account: string,
    password: string,
  ): Promise<{
    user: any;
    token: string;
  }> {
    const user = await this.userService.findOneByAccount(account);

    if (!user) {
      throw new UnauthorizedException('账户不存在');
    }

    const isPasswordValid = this.cryptoUtil.verifyPassword(
      password,
      user.password,
    );

    if (!isPasswordValid) {
      throw new UnauthorizedException('密码错误');
    }

    // 生成token
    const token = this.jwtService.sign({
      id: user.id,
      account: user.account,
      role: user.role,
    });

    // 删除密码字段
    const { password: _, ...userWithoutPassword } = user;

    return {
      user: userWithoutPassword,
      token,
    };
  }

  /**
   * 验证token
   * @param token token
   * @returns 解码后的用户信息
   */
  async verifyToken(token: string): Promise<any> {
    try {
      const payload = await this.jwtService.verifyAsync(token, {
        secret: 'your-secret-key',
      });
      return payload;
    } catch (error) {
      throw new UnauthorizedException('无效的token');
    }
  }
}
